import React, {Component} from 'react';

import {
  StyleSheet,
  Text,
  View,
  Platform,
  FlatList,
  Dimensions,
  TouchableOpacity,
  Image,
  ActivityIndicator,
} from 'react-native';

import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Constant from '../../utils/Constant'; //全局变量
import Header from '../../components/header';
import Loading from '../../utils/Loading';
import NoData from '../../utils/NoData';
import moment from 'moment';

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class SelectStorePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRefresh: false,
      showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      pageNo: 1,

      // 门店列表
      stores: [],
    };
  }

  render() {
    navigation = this.props.navigation;
    return (
        <View style={styles.container}>
          <Header navigation={navigation} Title={'选择门店'} />

          {/* 列表数据 */}
          {this.renderList()}

          <Loading onRef={ref => (this.Loading = ref)} />
        </View>
    );
  }

  componentDidMount() {
    this.refreshData();
  }

  renderList() {
    return (
        <View
            style={{
              flex: 1,
              marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
            }}>
          <FlatList
              data={this.state.stores}
              renderItem={this.renderItemView.bind(this)}
              extraData={this.state}
              onRefresh={this.refreshData}
              refreshing={this.state.isRefresh}
              ListEmptyComponent={this.renderEmpty.bind(this)}
              ListFooterComponent={this.renderFooter.bind(this)}
              onEndReached={this._onEndReached.bind(this)}
              onEndReachedThreshold={0.3}
          />
        </View>
    );
  }

  renderItemView({item, index}) {
    return (
        <TouchableOpacity key={item.id} style={styles.storeItem}
                          onPress={() => {
                            const { navigation, route } = this.props;
                            const onGoBack = route.params?.onGoBack;
                            if (onGoBack && typeof onGoBack === 'function') {
                              onGoBack(item.merchantId, item.merchantName); // 回传选中的门店 ID
                            }
                            navigation.goBack(); // 返回上一页
                          }}>
          <View style={styles.storeInfo}>
            <Text style={styles.storeName}>{item.merchantName ? item.merchantName : '暂无名称'}</Text>
            <Text style={styles.storeAddress}>{item.address ? item.address : '暂无地址'}</Text>
          </View>
          <Image
              style={styles.storeItemImg}
              source={require('source/image/seekCenter/right_arrow_icon.png')}
          />
        </TouchableOpacity>
    );
  }

  renderEmpty() {
    return <NoData Desc="暂无数据" style={{marginTop: gREM(200)}} />;
  }

  //刷新数据
  refreshData = () => {
    this.setState(
        {
          isRefresh: true,
          pageNo: 1,
          stores: [],
        },
        function () {
          this.getMerchant();
        },
    );
  };

  renderFooter() {
    if (this.state.showFoot === 1) {
      return null;
    } else if (this.state.showFoot === 2) {
      return (
          <View style={styles.footer}>
            <ActivityIndicator size="small" color="#999999" />
            <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
          </View>
      );
    } else if (this.state.showFoot === 0) {
      return null;
    }
  }

  _onEndReached() {
    //如果是正在加载中或没有更多数据了，则返回
    if (this.state.showFoot !== 0) {
      return null;
    }
    //底部显示正在加载更多数据
    this.setState(
        {
          showFoot: 2,
          pageNo: this.state.pageNo + 1,
        },
        function () {
          this.getMerchant();
        },
    );
  }

  getMerchant() {
    let param = {
      pageNo: this.state.pageNo,
      pageSize: 20,
      // memberClass: 40,
    }
    HttpUtils.postRequest(HttpUrls.getBuyerMerchantListPage, param)
        .then(result => {
          let data = result.data;
          if (data) {
            let resultList = data.resultList;
            if (resultList && resultList.length > 0) {
              this.setState({
                stores: this.state.stores.concat(resultList),
                isRefresh: false,
                showFoot: 1,
              });
              setTimeout(() => {
                this.setState({
                  showFoot: resultList.length >= 20 ? 0 : 1,
                });
              }, 200);
            } else {
              this.setState({
                showFoot: 1,
                isRefresh: false,
              });
            }
          } else {
            this.setState({
              showFoot: 1,
              isRefresh: false,
            });
          }
        })
        .catch(error => {});
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9F9F9',
  },

  contractCount: {
    fontWeight: '400',
    fontSize: 14,
    color: '#333333',
    marginLeft: 15,
  },

  contractStatus: {
    fontWeight: '400',
    fontSize: 14,
    color: '#ED542E',
  },

  footer: {
    flexDirection: 'row',
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f6f6f6',
  },
  loadMoreTextStyle: {
    fontSize: 14,
    color: '#999999',
    marginStart: 10,
  },

  // 门店列表样式
  storeItemImg: {
    width: 18,
    height: 18,
  },
  storeList: {
    backgroundColor: '#fff',
  },
  storeItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 18,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#f0f0f0',
  },
  storeInfo: {
    flex: 1,
    marginRight: 10,
  },
  storeName: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginBottom: 6,
  },
  storeAddress: {
    fontSize: 14,
    color: '#999',
  },
});
